#include <gdbio/qtRioNet.h>

using namespace mopenocd;

qtServerIO::qtServerIO()
{
    sk = nullptr;
}

int qtServerIO::open(const char *dev, long port)
{
    QHostAddress a(dev);

    _sv.setMaxPendingConnections(1);
    if (!_sv.listen(a, port))
    {
        qDebug("listen fail\n");
        return -1;
    }

    _sv.waitForNewConnection(-1);
    sk = _sv.nextPendingConnection();

    return 0;
}

void qtServerIO::close()
{
    _sv.close();

    sk->close();
    delete sk;
    sk = nullptr;
}

int qtServerIO::read(void *buf, uint32_t max, int timeout_ms)
{
    int ret = 0;

    if (sk == nullptr)
        return -1;

    if (sk->state() != QTcpSocket::ConnectedState)
        return -1;

    if (sk->bytesAvailable() == 0)
    {
        if (!sk->waitForReadyRead(timeout_ms))
            return 0;
    }

    ret = sk->read((char*)buf, max);

    return ret;
}

int qtServerIO::write(const void *buf, uint32_t max, int timeout_ms)
{
    int ret;

    if (sk == nullptr)
        return -1;

    ret = sk->write((const char*)buf, max);
    sk->waitForBytesWritten();

    return ret;
}

bool qtServerIO::nextReadReady()
{
    if (sk->bytesAvailable() > 0)
        return true;

    return false;
}
